package mhttp

import (
	"bytes"
	"compress/gzip"
	"errors"
	"gitee.com/dennis-mxx/mxx-core-v2/mutil"
	"github.com/goccy/go-json"
	"io"
	"net/http"
	"strings"
)

type Response struct {
	Url           string
	Method        string
	Status        string
	StatusCode    int
	OK            bool
	ContentLength int64
	Data          *bytes.Buffer
	Header        http.Header
	Metadata      *http.Response
	buff          *bytes.Buffer
	reader        bool
}

func (ce *Response) Cookie() []*http.Cookie {
	return ce.Metadata.Cookies()
}

func (ce *Response) ContentType() string {
	return ce.GetHeader("Content-Type")
}

func (ce *Response) GetHeader(name string) string {
	return ce.Header.Get(name)
}

func (ce *Response) Charset() string {
	return ce.Header.Get("Accept-Charset")
}

func (ce *Response) Json(dest any) error {
	if err := ce.read(); err != nil {
		return err
	}
	if err := json.Unmarshal(ce.buff.Bytes(), dest); err != nil {
		return err
	}
	return nil
}
func (ce *Response) Str() (string, error) {
	if err := ce.read(); err != nil {
		return "", err
	}
	return string(ce.buff.Bytes()), nil
}

func (ce *Response) Buffer() (*bytes.Buffer, error) {
	if err := ce.read(); err != nil {
		return nil, err
	}
	return ce.buff, nil
}

func (ce *Response) read() error {
	if ce.reader {
		return nil
	}
	if ce.buff != nil {
		return nil
	}

	if ce.Metadata != nil && ce.Metadata.Body != nil {
		ce.reader = true
		if buffer, err := mutil.ReadBuffer(ce.Metadata.Body); err == nil {
			encode := ce.Metadata.Header.Get("content-encoding")
			if encode != "" && strings.Contains(encode, "gzip") {
				if red, err := gzip.NewReader(buffer); err == nil {
					if b, err := io.ReadAll(red); err == nil {
						ce.buff = bytes.NewBuffer(b)
					} else {
						return err
					}
				} else {
					return err
				}
			} else {
				ce.buff = buffer
			}

			return nil
		} else {
			return err
		}
	}
	return errors.New("response is null")
}
